//
//  TFDataCapturer.m
//  WeChatBuniess
//
//  Created by Guo Rui on 2017/12/22.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "TFDataCapturer.h"
#import "TFWeakTimer.h"
const static NSInteger POST_ITEM_COUNT = 20;

@interface TFDataCapturer()
@property (nonatomic, strong, readwrite) NSMutableSet<WCDataItem *> *dataItemsSet;
@property (nonatomic, strong, readwrite) NSMutableSet<NSString *>   *itemIdsSet;
@property (nonatomic, assign, readwrite) BOOL                       captureCompleted;
@property (strong, nonatomic) dispatch_queue_t serialQueue;
@property (strong, nonatomic) TFWeakTimer *timer;
@end

@implementation TFDataCapturer
- (void)startTimer
{
    NSLog(@"启动定时器");
    self.timer = [TFWeakTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(ondo) userInfo:nil repeats:YES dispatchQueue:dispatch_get_main_queue()];
}

- (void)stopTimer
{
    NSLog(@"关闭定时器");
    [self.timer invalidate];
    self.timer = nil;
    self.burstBlock = nil;
}

- (void)ondo
{
    if (self.burstBlock) {
        self.burstBlock();
    }
}
//MARK: - init
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.dataItemsSet = [NSMutableSet new];
        self.itemIdsSet = [NSMutableSet new];
        self.serialQueue = dispatch_queue_create("cn.timeface.wechatbuniess.tfdatacapture.queue", NULL);
        self.captureCompleted = NO;
    }
    return self;
}

//MARK: - data
- (void)updateWCDataItem:(WCDataItem *)dataItem withItemId:(id)itemId {
    __weak TFDataCapturer *weakSelf = self;
    dispatch_async(_serialQueue, ^{
        if (![_itemIdsSet containsObject:itemId] && (dataItem.contentObj.type == 1 || dataItem.contentObj.type == 2)){
            [weakSelf.dataItemsSet addObject:dataItem];
            [weakSelf.itemIdsSet addObject:itemId];
            NSLog(@"TFDataCapturer - 开始接收数据 %@", itemId);
        }
        
        if (weakSelf.dataItemsSet.count == POST_ITEM_COUNT&&weakSelf.SendDataPer20Block) {
                weakSelf.SendDataPer20Block([weakSelf.dataItemsSet allObjects],weakSelf.itemIdsSet.count);
                [weakSelf.dataItemsSet removeAllObjects];
        }
    });
}

- (void)reciveDataComplate {
    [self stopTimer];
    
    self.captureCompleted = YES;
    __weak TFDataCapturer *weakSelf = self;
    dispatch_sync(_serialQueue, ^{
        if (weakSelf.SendDataPer20Block) {
            weakSelf.SendDataPer20Block([weakSelf.dataItemsSet allObjects],weakSelf.itemIdsSet.count);
            [weakSelf.dataItemsSet removeAllObjects];
        }
    });
    if (self.reciveDataCompletion) {
        self.reciveDataCompletion();
    }
}

- (void)clean {
    self.captureCompleted = NO;
    [self.dataItemsSet removeAllObjects];
    [self.itemIdsSet removeAllObjects];
    
}

@end
